const ipRoot = 'https://gala.wisq.cn/';
// 定义一个flag 判断是否刷新Token中
let isRefreshing = false;
const token = wx.getStorageSync('token');
// 获取token的过期时间
const token_time = wx.getStorageSync('token_time');
let expires_in = parseInt(token_time) + 7200

// 刷新token，只需要重新获取一次即可
if (expires_in - parseInt(token_time) <= 600) { // 当access_token的有效期不足10分钟时，触发刷新
    updateToken();
}

const post = (path, data = {}, showLoading = false, method = 'post') => {
    if (showLoading) {
        wx.showLoading({
            title: '加载中..',
            mask: true
        })
    }
    return new Promise((resolve, reject) => {
        wx.request({
            url: ipRoot + path,
            data: data,
            method: method ? 'post' : method,
            header: {
                'content-type': 'application/json',
                'token': wx.getStorageSync('token')
            },
            success: (res) => {
                if (res.data.code === 1) {
                    resolve(res.data)
                } else {
                    wx.showToast({
                        title: res.data.msg,
                        icon: 'none'
                    })
                    resolve(res)
                }

            },
            fail(err) {
                reject(err) && wx.hideLoading()
            },
            complete(res) {
                showLoading && wx.hideLoading()
            }
        })
    })
}
const uploadFile = (url, data, noRefetch) => {
    var url = ipRoot + url;
    return new Promise((resolve, reject) => {
        wx.uploadFile({
            url: url,
            filePath: data.path,
            name: 'file',
            formData: {},
            success: function (res) {
                var data = JSON.parse(res.data);
                resolve(data);
            },
            fail: function (res) {
                console.log('fail:', res);
            }
        })
    })
}
// 刷新token
function updateToken() {
    post('api/token/refresh', null, 0, 'get').then(res => {
        let code = res.data.code
        if (code == 1) {
            wx.setStorageSync('token', res.data.token);
        } else {
            wx.switchTab({
                url: '/pages/my/index'
            })
        }
    })
}
module.exports = {
    post,
    ipRoot,
    uploadFile
}